package com.doubao.hardware.service.impl;

import com.doubao.hardware.entity.DeviceConfigEntity;
import com.doubao.hardware.mapper.DeviceConfigMapper;
import com.doubao.hardware.model.DeviceConfig;
import com.doubao.hardware.service.DeviceConfigService;
import com.doubao.hardware.service.MqttService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;

/**
 * 设备配置服务实现类
 * 负责设备配置的管理和操作
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class DeviceConfigServiceImpl implements DeviceConfigService {

    private final MqttService mqttService;
    private final ObjectMapper objectMapper;
    private final DeviceConfigMapper deviceConfigMapper;

    @Override
    public void updateDeviceConfig(String deviceId, DeviceConfig deviceConfig) {
        // 查询设备配置是否存在
        DeviceConfigEntity entity = deviceConfigMapper.selectByDeviceId(deviceId);

        if (entity == null) {
            // 创建新的设备配置
            entity = new DeviceConfigEntity();
            entity.setDeviceId(deviceId);
            entity.setConfig(deviceConfig);
            entity.setStatus(1); // 默认在线
            entity.setCreateTime(LocalDateTime.now());
            entity.setLastUpdateTime(LocalDateTime.now());

            deviceConfigMapper.insert(entity);
        } else {
            // 更新现有设备配置
            entity.setConfig(deviceConfig);
            entity.setLastUpdateTime(LocalDateTime.now());

            deviceConfigMapper.updateById(entity);
        }

        log.info("Device config updated and persisted for device: {}", deviceId);
    }

    @Override
    public DeviceConfig getDeviceConfig(String deviceId) {
        DeviceConfigEntity entity = deviceConfigMapper.selectByDeviceId(deviceId);

        if (entity == null) {
            log.warn("Device config not found for device: {}", deviceId);
            return null;
        }

        return entity.getConfig();
    }

    @Override
    public void restartDevice(String deviceId) {
        log.info("Sending restart command to device: {}", deviceId);
        // 发送重启命令到设备
        mqttService.sendMessageToTopic("doubao/hardware/command/" + deviceId + "/restart", "restart");
    }

    @Override
    public void syncDeviceConfig(String deviceId) {
        DeviceConfig config = getDeviceConfig(deviceId);
        if (config != null) {
            try {
                String configJson = objectMapper.writeValueAsString(config);
                log.info("Syncing device config to device: {}", deviceId);
                // 发送配置同步命令到设备
                mqttService.sendMessageToTopic("doubao/hardware/command/" + deviceId + "/sync", configJson);
            } catch (Exception e) {
                log.error("Error syncing device config", e);
            }
        } else {
            log.warn("Cannot sync config for device: {}, config not found", deviceId);
        }
    }
}